package com.fw.ui.view.profile.service.event;

import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.fw.service.bean.SearchCriteriaBean;
import com.fw.service.serviceprofile.bean.SearchServiceProfileBean;
import com.fw.ui.ApplicationUI;
import com.fw.ui.bao.MessageBAO;
import com.fw.ui.bao.PropertyBAO;
import com.fw.ui.bao.ServiceProfileBAO;
import com.fw.ui.util.SessionInfoUtils;
import com.fw.ui.util.UICommonUtils;
import com.fw.ui.util.VaadinApplicationObjectSupport;
import com.fw.ui.view.common.SortingTablePanel;
import com.fw.ui.view.common.TablePanel;
import com.fw.ui.view.common.util.FileStreamSource;
import com.fw.ui.view.event.AbstractButtonClickListener;
import com.fw.ui.view.profile.SearchServiceProfileView;
import com.vaadin.server.Page;
import com.vaadin.server.StreamResource;
import com.vaadin.ui.Button.ClickEvent;

@Component
@Scope(SCOPE_PROTOTYPE)
public class SearchServiceProfileExportButtonClickListener extends AbstractButtonClickListener {

    private static final long serialVersionUID = 1L;

    @Autowired
    protected transient VaadinApplicationObjectSupport app;
    @Autowired
    private PropertyBAO propertyBAO;
    @Autowired
    private UICommonUtils uiCommonUtils;
    @Autowired
    private ServiceProfileBAO serviceProfileBAO;
    @Autowired
    private SessionInfoUtils sessionInfoUtils;

    @SuppressWarnings("deprecation")
    @Override
    public Map<String, Object> click(ClickEvent event) throws Exception {
	Map<String, Object> map = new HashMap<String, Object>();
	try {
	    // SearchServiceProfileView searchServiceProfileView = (SearchServiceProfileView) this.getBasedComponent();
	    SearchCriteriaBean<SearchServiceProfileBean> searchCriteriaBean = this.getSearchCriteriaBean();
	    byte[] bytes = serviceProfileBAO.exportServiceProfileAsCSV(searchCriteriaBean);
	    if (bytes != null) {
		String filenamePrefix = propertyBAO
			.getPropertyValue("com.fw.ui.view.profile.SearchServiceProfileView.export.filename.prefix");
		String filename = filenamePrefix + new Date().getTime() + ".csv";
		FileStreamSource fileStreamSource = new FileStreamSource(bytes);
		StreamResource resource = new StreamResource(fileStreamSource, filename);

		// FileDownloader fileDownloaderCSV = new FileDownloader(resource);
		// fileDownloaderCSV.setFileDownloadResource(resource);
		// fileDownloaderCSV.extend(searchServiceProfileView.getBtnExport());

		Page.getCurrent().open(resource, null, false);

	    } else {
		map.put(MessageBAO.MESSAGE_WARNING_TYPE, "com.fw.ui.view.profile.SearchServiceProfileView.message.export.nodata");
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	    map.put(MessageBAO.MESSAGE_WARNING_TYPE, "com.fw.ui.view.profile.SearchServiceProfileView.message.export.failed");
	}
	return map;
    }

    private SearchCriteriaBean<SearchServiceProfileBean> getSearchCriteriaBean() {
	SearchServiceProfileView searchServiceProfileView = (SearchServiceProfileView) this.getBasedComponent();

	TablePanel tablePanel = searchServiceProfileView.getTablePanel();
	SortingTablePanel sortingTablePanel = tablePanel.getSortingTablePanel();

	Integer size = tablePanel.getManualPageSize();
	int page = 1;

	String sort1 = (String) sortingTablePanel.getCbbSelectSort1().getValue();
	String sort2 = (String) sortingTablePanel.getCbbSelectSort2().getValue();
	String sort3 = (String) sortingTablePanel.getCbbSelectSort3().getValue();
	String sortType1 = (String) sortingTablePanel.getOpgSortingType1().getValue();
	String sortType2 = (String) sortingTablePanel.getOpgSortingType2().getValue();
	String sortType3 = (String) sortingTablePanel.getOpgSortingType3().getValue();

	Map<String, String> sortMap = new LinkedHashMap<String, String>();
	if (sort1 != null) {
	    sortMap.put(sort1, sortType1);
	}
	if (sort2 != null && !sortMap.containsKey(sort2)) {
	    sortMap.put(sort2, sortType2);
	}
	if (sort3 != null && !sortMap.containsKey(sort3)) {
	    sortMap.put(sort3, sortType3);
	}

	SearchServiceProfileBean searchServiceProfileBean = new SearchServiceProfileBean();

	searchServiceProfileBean.setServiceId((String) searchServiceProfileView.getCbbServiceId().getValue());
	searchServiceProfileBean.setMerchantId((String) searchServiceProfileView.getCbbMerchantId().getValue());
	searchServiceProfileBean.setMerchantName((String) searchServiceProfileView.getCbbMerchantName().getValue());
	searchServiceProfileBean.setCompanyName((String) searchServiceProfileView.getCbbCompanyName().getValue());
	searchServiceProfileBean.setProjectContact((String) searchServiceProfileView.getCbbProjectContact().getValue());
	searchServiceProfileBean.setHideServiceTest((Boolean) searchServiceProfileView.getCbHideServiceTest().getValue());
	searchServiceProfileBean.setBankGuaranteeExpireDateFrom(searchServiceProfileView.getPdfBankGuaranteeExpireDateFrom().getValue());
	searchServiceProfileBean.setBankGuaranteeExpireDateTo(searchServiceProfileView.getPdfBankGuaranteeExpireDateTo().getValue());
	searchServiceProfileBean.setLaunchedDateFrom(searchServiceProfileView.getPdfLaunchedDateFrom().getValue());
	searchServiceProfileBean.setLaunchedDateTo(searchServiceProfileView.getPdfLaunchedDateTo().getValue());
	searchServiceProfileBean.setMdr((String) searchServiceProfileView.getCbbMdr().getValue());
	searchServiceProfileBean.setServiceFee((String) searchServiceProfileView.getCbbServiceFee().getValue());
	searchServiceProfileBean.setHost((String) searchServiceProfileView.getCbbHost().getValue());

	// searchServiceProfileBean.setServiceStatus((String) searchServiceProfileView.getCbbStatus().getValue());
	// searchServiceProfileBean.setServiceType((String) searchServiceProfileView.getCbbServiceType().getValue());
	searchServiceProfileBean.setServiceType(((searchServiceProfileView.getCbbServiceType().getValue() == null
		|| searchServiceProfileView.getCbbServiceType().getValue().toString().trim().length() == 0 || searchServiceProfileView
		.getCbbServiceType().getValue().toString().trim().equals("0")) ? null : searchServiceProfileView.getCbbServiceType()
		.getValue().toString()));
	searchServiceProfileBean.setServiceStatus(((searchServiceProfileView.getCbbStatus().getValue() == null
		|| searchServiceProfileView.getCbbStatus().getValue().toString().trim().length() == 0 || searchServiceProfileView
		.getCbbStatus().getValue().toString().trim().equals("0")) ? null : searchServiceProfileView.getCbbStatus().getValue()
		.toString()));

	ApplicationUI applicationUI = (ApplicationUI) searchServiceProfileView.getUI();
	sessionInfoUtils.setSessionInfoDetails(searchServiceProfileBean, applicationUI.getAuthenticationBean(), applicationUI.getLocale());

	SearchCriteriaBean<SearchServiceProfileBean> searchCriteriaBean = new SearchCriteriaBean<SearchServiceProfileBean>();
	if (!sortMap.isEmpty()) {
	    searchCriteriaBean.setSortingCriteria(sortMap);
	} else {
	    String sortingDefault = this.propertyBAO
		    .getPropertyValue("com.fw.ui.view.profile.SearchServiceProfileView.default.table.sorting");
	    searchCriteriaBean.setDirection1(SearchCriteriaBean.DIRECTION_DESC);
	    searchCriteriaBean.setOrder1(sortingDefault);
	}

	searchCriteriaBean.setCriteriaBean(searchServiceProfileBean);
	searchCriteriaBean.setPage(page);
	searchCriteriaBean.setSize(size);
	return searchCriteriaBean;
    }

    @Override
    public boolean validate(ClickEvent event) {
	// SearchServiceProfileView searchServiceProfileView = (SearchServiceProfileView) this.getBasedComponent();
	// Collection<Extension> extensions = searchServiceProfileView.getBtnExport().getExtensions();
	// for (Extension extension : new ArrayList<Extension>(extensions)) {
	// searchServiceProfileView.getBtnExport().removeExtension(extension);
	// }
	return true;
    }

}
